<?php
// 本类由系统自动生成，仅供测试用途
class ControlTableAction extends CommonAction {
	function _filter(&$map) {
		$map['removed']=1;
		$map ['userid'] = array (
				'like',
				"%" . $_POST ['user'] . "%" 
		);
// 		if('1'!==$_SESSION [C ( 'USER_AUTH_KEY' )]){
// 			$map['operator']=$_SESSION [C ( 'USER_AUTH_KEY' )];
// 		}
	}
	public function _before_index() {
		$model = M ( "ControlTable" );
		$list = $model->select ();
		$model3 = M ( "Carrier" );
		$Carrier = $model3->select ();
		$model2 = M ( "Provider" );
		$Provider=$model2->select ();
		$model4 = M ( "Customer" );
		$Customer=$model4->select ();
		//按照controldate(调度时间升序)排序
		$_REQUEST['_order'] = 'controldate';
		$_REQUEST['_sort'] = 'desc';
		$this->assign ( 'carr', $Carrier );
		$this->assign ( 'provider', $Provider );
		$this->assign ( 'groupList', $list );
		$this->assign ( 'customer', $Customer );
	}
	public function read(){
		$id=$_REQUEST['id'];
		$model=M('ControlTable');
		$ControlTable=$model->where('id='.$id)->find();
		$model3 = M ( "Carrier" );
		$Carrier=$model3->where('id='.$ControlTable['carrier'])->find();
		$model2 = M ( "Provider" );
		$Provider=$model2->select ();
		$model4 = M ( "Customer" );
		$Customer=$model4->select ();
		$this->assign ( 'customer', $Customer );
		$this->assign('carrier',$Carrier);
		$this->assign ( 'provider', $Provider );
		$this->assign('vo',$ControlTable);
		$this->display();
	}
	public function _before_add() {
		/**
		 * 下拉框显示信息
		 */
		// $model1 = M ( "StoreManage" );
		// $ShortMessage = $model1->select ();
		$id=$_REQUEST['id'];
		$model2 = M ( "Provider" );
		$model1 = M('ContractLog');
		$Conlog = $model1->find($id);
		$Provider = $model2->select ();
		// 客户信息
		$model4 = M ( "Customer" );
		$Customer = $model4->where('removed!=2')->select ();
		$model3 = M ( "Carrier" );
		$Carrier = $model3->select ();
		// //获得子公司的信息
		$this->getSubCompany ();
		// 获得商品信息
		$this->getGoods ();
		/*
		 * $model4 = M ( "Car" ); $Car = $model4->where ( 'status=1' )->select
		 * ();
		 */
		//如果是客户合同的拟定调度，则带回客户的值.否则带回供应商的信息
		if($Conlog['type']==1){
			$this->assign('customer',$Conlog['secondname']);
			$this->assign('customerid',$Conlog['secondid']);
		}else{
			if($Conlog['type']==2){
				$this->assign('provider',$Conlog['secondname']);
				$this->assign('providerid',$Conlog['secondid']);
			}
		}
		//当该拟定调度payondelivery值为1时，关于改拟定调度信息生成的调度提示为款到卸车
		if($Conlog['payondelivery']==1){
			$this->assign('payondelivery',1);
		}
		$this->assign('product',$Conlog['goodname']);
		$model = M ( "ControlTable" );
		$list = $model->select ();
		$this->assign ( 'list', $list );
		// $this->assign ( 'list1', $ShortMessage );
		$this->assign ( 'list2', $Provider );
		$this->assign ( 'list3', $Carrier );
		$this->assign ( 'list4', $Customer );
		/* $this->assign ( 'list4', $Car ); */
		$userModel = M ( 'User' );
		$user = $userModel->query('SELECT  *  FROM  `mlt_user` ORDER BY CONVERT( fullname USING gbk ) COLLATE gbk_chinese_ci ASC;');
		$this->assign ( 'user', $user );
		$freightModel = M ( 'Freight' );
		$freight = $freightModel->distinct ( true )->field ( 'startaddress' )->select ();
		$end = $freightModel->distinct ( true )->field ( 'endaddress' )->select ();
		$this->assign ( 'freight', $freight );
		$this->assign ( 'end', $end );
		$this->assign('contractlogid',$id);
	}
	function editton() {
            if("true"==$_REQUEST['updateton']){
            	$this->_before_updateton();
            	$this->updateton();
            }
	}
	public function _before_edit() {
		/**
		 * 下拉框显示信息
		 */
		$id = $_REQUEST ['id'];
		$model = M ( "ControlTable" );
		$model3 = M ( "Carrier" );
		$Carrier = $model3->select ();
		$model2 = M ( "Provider" );
		$Provider = $model2->select ();
		$model4 = M ( "Car" );
		$Car = $model4->select ();
		// $model5 = M ( 'StoreManage' );
		// $StoreManage = $model5->select ();
		$model6 = M ( "Customer" );
		$Customer = $model6->select ();
		
		// //获得子公司的信息
		$this->getSubCompany ();
		
		// 获得商品信息
		$this->getGoods ();
		$this->assign ( 'list3', $Carrier );
		$this->assign ( 'list2', $Provider );
		$this->assign ( 'list4', $Car );
		// $this->assign ( 'list5', $StoreManage );
		$this->assign ( 'list6', $Customer );
		$userModel = M ( 'User' );
		$user = $userModel->select ();
		$this->assign ( 'user', $user );
		$freightModel = M ( 'Freight' );
		$freight = $freightModel->distinct ( true )->field ( 'startaddress' )->select ();
		$end = $freightModel->distinct ( true )->field ( 'endaddress' )->select ();
		$this->assign ( 'freight', $freight );
		$this->assign ( 'end', $end );
	}
	
	// 获得子公司的信息
	public function getSubCompany() {
		$Company = M ( 'Company' );
		$subcompany = $Company->select ();
		$this->assign ( 'subcompany', $subcompany );
	}
	// 获得商品信息
	public function getGoods() {
		$Goods = M ( 'Goods' );
		$goodslist = $Goods->select ();
		$this->assign ( 'goods', $goodslist );
	}
	public function _before_insert() {
		$customerid = $_REQUEST ['customer']; // 客户
		$destination = $_REQUEST ['destination']; // 目的地
		$product = $_REQUEST ['product']; // 产品名称
		$start = $_REQUEST ['start']; // 起始地
		$providerid = $_REQUEST ['provider']; // 供应商
		//拟定调度表的ID
		$contractlogid = $_REQUEST['contractlogid'];
		$model1 = M('ContractLog');
		$model2 = M ( "Provider" );
		$model3 = M ( "StoreManage" );
		$model4 = M ( "Customer" );
		$model5 = M('CustomerGood');
	    if ($customerid){
			$customers=$model4->where('id='.$customerid)->find();
			$customer=$customers['customername'];
			$map['customerid']=$customerid;
		}else{
			$map['customerid']=null;
			$customer=null;
		}
		if($providerid){
			$provider = $model2->where('id='.$providerid)->find();
			$providername = $provider['providername'];
		}else{
			$providername=null;
		}
    	$map['goodname']=$product;
		$cusgood = $model5->where($map)->select();
		//判断仓库之间，起始地目的地之间是否相同
		$storenameA='storeA';
		$storenameB='storeB';
		$storenameC='storeC';
		if($customer=="东明库"){
			if($providername=="东明库"){
				$this->error('客户与供应商不能同时为东明库！');
			}else{
				if($start=="东明库"){
					$this->error('客户与起始地不能同时为东明库！');
				}else{
					if($destination!=="东明库"){
						$this->error('客户为东明库时目的地必须为东明库！');
					}
				}
			}
		}
		if($customer=="南曹库"){
			if($providername=="南曹库"){
				$this->error('客户与供应商不能同时为南曹库！');
			}else{
				if($start=="南曹库"){
					$this->error('客户与起始地不能同时为南曹库！');
				}else{
					if($destination!=="南曹库"){
						$this->error('客户为南曹库时目的地必须为南曹库！');
					}
				}
			}
		}
		if($customer=="金海库"){
			if($providername=="金海库"){
				$this->error('客户与供应商不能同时为金海库！');
			}else{
				if($start=="金海库"){
					$this->error('客户与起始地不能同时为金海库！');
				}else{
					if($destination!=="金海库"){
						$this->error('客户为金海库时目的地必须为金海库！');
					}
				}
			}
		}
		if($providername=="东明库"){
			if($destination=="东明库"){
				$this->error('供应商与目的地不能同时为东明库！');
			}else{
				if($start!=="东明库"){
					$this->error('供应商为东明库时起始地必须为东明库！');
				}
			}
		}
		if($providername=="南曹库"){
			if($destination=="南曹库"){
				$this->error('供应商与目的地不能同时为南曹库！');
			}else{
				if($start!=="南曹库"){
					$this->error('供应商为南曹库时起始地必须为南曹库！');
				}
			}
		}
		if($providername=="金海库"){
			if($destination=="金海库"){
				$this->error('供应商与目的地不能同时为金海库！');
			}else{
				if($start!=="金海库"){
					$this->error('供应商为金海库时起始地必须为金海库！');
				}
			}
		}
		if($destination=="东明库"){
			if($customer!=="东明库"){
				$this->error('目的地为东明库时客户必须为东明库！');
			}
		}
		if($destination=="南曹库"){
			if($customer!=="南曹库"){
				$this->error('目的地为南曹库时客户必须为南曹库！');
			}
		}
		if($destination=="金海库"){
			if($customer!=="金海库"){
				$this->error('目的地为金海库时客户必须为金海库！');
			}
		}
		if($start=="东明库"){
			if($providername!=="东明库"){
				$this->error('起始地为东明库时供应商必须为东明库！');
			}
		}
		if($start=="南曹库"){
			if($providername!=="南曹库"){
				$this->error('起始地为南曹库时供应商必须为南曹库！');
			}
		}
		if($start=="金海库"){
			if($providername!=="金海库"){
				$this->error('起始地为金海库时供应商必须为金海库！');
			}
		}
		if($start==$destination){
			$this->error('起始地目的地不能相同！');
		}
		 
		//判断仓库是否存在相关商品
		if ($customer == "东明库" ||$destination=="东明库"||$start == "东明库" || $providername == "东明库") {
			$d = $model3->where('storename=\''.$storenameA.'\''.' and product=\''.$product.'\'')->select();
			if (! $d) {
				$this->error ('东明库列表不存在' . $product . '相关物品!');
			}
		}
		if ($customer == "南曹库" ||$destination=="南曹库"||$start == "南曹库" || $providername == "南曹库") {
			$n = $model3->where('storename=\''.$storenameB.'\''.' and product=\''.$product.'\'')->select();
			if (! $n) {
				$this->error ('南曹库列表不存在' . $product . '相关物品!');
			}
		}
		if ($customer == "金海库" ||$destination=="金海库"||$start == "金海库" || $providerid == "金海库") {
			$j = $model3->where('storename=\''.$storenameC.'\''.' and product=\''.$product.'\'')->select();
			if (! $j) {
				$this->error ('金海库列表不存在' . $product . '相关物品!');
			}
		}
	//判断客户是否存在该商品
		if($customer!=="金海库"&&$customer!=="东明库"&&$customer!=="南曹库"){
			$model6 = M('CustomerGood');
			$cusgood=$model6->where('customerid='.$customerid)->select();
			$tru=false;
			for($i=0;$i<count($cusgood);$i++){
				if($cusgood[$i]['product']==$product){
					$tru=true;
				}
			}
			if(!$tru){
				$this->error('本客户不存在'.$product.'物品！');
			}
		}
		//当拟定调度的payondelivery值为1时关于该信息的调度payondelivery值也为1（款到卸车）
		$conlog = $model1->find($contractlogid);
		if($conlog['payondelivery']==1){
			$_POST['payondelivery']=1;
		}else{
			$_POST['payondelivery']=0;
		}
	}
	public function _before_updateton(){
		$model = M ( 'ControlTable' );
		$id = $_REQUEST ['id'];
		$vo = $model->getById ( $id );
		if($vo['sweight']!==null&&$vo['eweight']!==null&&$vo['sweight']!==""&&$vo['eweight']!==""&&$vo['sweight']!=='0'&&$vo['eweight']!=='0'){
			$this->error('已输入吨数信息，不可更改!');
		}
	}
	//吨数录入
    public function updateton() {
		$id=$_REQUEST['id'];
		$model1 = M ( 'CarrierDispatch' );
		$model2 = M('ContractLog');
		$carstat=$_REQUEST['carstat'];
		$sweight=bcsub($_REQUEST['eweight'],$_REQUEST['sweight'],4);// 出厂净重=毛重-皮重
		$model = M ( 'Provider' );
		//开启事务
		$model2->startTrans();
		$result=true;
		$result1 = true;
		$RSMDM = true;
		$RSMNC = true;
		$RSMJH = true;
		$model3 = M ( "StoreManage" );
		$model4 = M('ControlTable');
		$model5=M('ControlLog');
		$ControlTable=$model4->where('id='.$id)->find();
		$providername = $ControlTable['provider'];//供应商
		$shipper = $ControlTable['shipper']; // 发货方
		$customer = $ControlTable['customer']; // 客户
		$product = $ControlTable['product']; // 产品名称
		$start = $ControlTable['start']; // 起始地
		$destination = $ControlTable['destination']; // 目的地
		$carrier = $ControlTable['carrier']; // 承运方
		$carno = $ControlTable['carno']; // 车牌号
		$orders = $ControlTable['orders']; // 订单号
		//判断输入的吨数是否大于拟定调度要求的可调度吨数
		$ContractLog = $model2->find($ControlTable['contractlogid']);
		//拟定调度表可调度吨数
		$capacity = $ContractLog['capacity'];
		//拟定调度表已调度吨数
		$alshipment = $ContractLog['alshipment'];
		//本次调度后已调度吨数
		$afteralshipment=bcadd($alshipment,$sweight,4);
// 		if($sweight>(bcsub($capacity,$alshipment,4))){
// 			$this->error("毛重-皮重（出场净重）大于可调度吨数，请确认！");
// 		}else{
// 			$datactlog['alshipment']=$afteralshipment;
// 			$datactlog['status'] = ($datactlog['alshipment']/$capacity)*100;
// 		}
		$datactlog['alshipment']=$afteralshipment;
		$datactlog['status'] = ($datactlog['alshipment']/$capacity)*100;
		// 修改供应商供应表信息
		$Provider = $model->where ( 'id=\'' . $providername . '\'' )->find ();
		if (""==$providername||($Provider['providername']=="南曹库")||($Provider['providername']=="东明库")||($Provider['providername']=="金海库")) {
			$storenameA='storeA';
			$storenameB='storeB';
			$storenameC='storeC';
			// 当起始地或供应商选择为仓库时
			if ($start == "东明库") {
				if($destination=="东明库"){
					$model2->rollback();
					$this->error ("起始地目的地不能同时为东明库！");
				}else{
					$Astoremanage = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameA.'\'' )->select ();
					if ($Astoremanage) {
						$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
						if ($datage ['stock'] < 0) {
							$model2->rollback();
							$this->error ('东明库存不足！');
						}else{
							$RSMDM = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameA.'\'' )->save($datage);
						}
					} else {
						$model2->rollback();
						$this->error ( '东明库列表不存在' . $product . '相关物品!');
					}
				}
			}
			if ($start == "南曹库") {
				if($destination == "南曹库"){
					$model2->rollback();
					$this->error ("起始地目的地不能同时为南曹库！");
				}else{
					$Astoremanage = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameB.'\'' )->select ();
					if ($Astoremanage) {
						$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
						if ($datage ['stock'] < 0) {
							$model2->rollback();
							$this->error ( '南曹库库存不足！');
						}else{
							$RSMNC = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameB.'\'' )->save($datage);
						}
					} else {
						$model2->rollback();
						$this->error ( '南曹库列表不存在' . $product . '相关物品!');
					}
				}
			}
			if ($start == "金海库") {
				if($destination == "金海库"){
					$model2->rollback();
					$this->error ("起始地目的地不能同时为金海库！" );
				}else{
					$Astoremanage = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameC.'\'' )->select ();
					if ($Astoremanage) {
						$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
						if ($datage ['stock'] < 0) {
							$model2->rollback();
							$this->error ( '金海库库存不足！' );
						}else{
							$RSMJH = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameC.'\'' )->save($datage);
						}
					} else {
						$model2->rollback();
						$this->error ('金海库列表不存在' . $product . '相关物品!');
					}
				}
			}
		}else{
			if ($shipper == "普天") {
				$data ['wshipment1'] = bcsub($Provider ['wshipment1'],$sweight,4);
				$i = 1;
			} else {
				if ($shipper == "兰亭") {
					$data ['wshipment2'] = bcsub($Provider ['wshipment2'],$sweight,4);
					$i = 2;
				} else {
					if ($shipper == "天地") {
						$data ['wshipment3'] = bcsub($Provider ['wshipment3'],$sweight,4);
						$i = 3;
					}
				}
			}
			if ($data ['wshipment' . $i] < 0) {
				$model2->rollback();
				$this->error ($shipper."对应的供应商无足够货物可用");
			} else {
				$result = $model->where ( 'id=\'' . $providername . '\'' )->save ( $data );
			}
		}
		// 增加租车信息
		if (""!==$ControlTable['carrier']) {
			$map ['carrierid'] = $carrier;
			$map ['sendername'] = $shipper;
			$map ['customer'] = $customer;
			$map ['providername'] = $providername;
			$map ['carno'] = $carno;
			$map ['beginning'] = $start;
			$map ['destination'] = $destination;
			$map ['cweight'] = $sweight;
			$map ['status'] = 0;
			$map ['orders'] = $orders;
			$result1 = $model1->add ( $map );
		}
	  //当客户选项或目的地选择为:仓库 时
		if ($customer == "东明库" || $destination == "东明库") {
			$storemanagedata = $model3->where('storename=\''.$storenameA.'\'')->getByProduct ( $product );
			if (! $storemanagedata) {
				$model2->rollback();
				$this->error ('东明库列表不存在' . $product . '相关物品!');
			}
		}
	  //南曹库判断
		if ($customer == "南曹库" || $destination == "南曹库") {
			$storemanagedata = $model3->where('storename=\''.$storenameB.'\'')->getByProduct ( $product );
			if (! $storemanagedata) {
				$model2->rollback();
				$this->error ('南曹库列表不存在' . $product . '相关物品!');
			}
		}
		
		//金海库判断
		if ($customer == "金海库" || $destination == "金海库") {
			$storemanagedata = $model3->where('storename=\''.$storenameC.'\'')->getByProduct ( $product );
			if (! $storemanagedata) {
				$model2->rollback();
				$this->error ('金海库列表不存在' . $product . '相关物品!');
			}
		}
		$data4['id']=$_REQUEST['id'];
		$data4['sweight']=$_REQUEST['sweight'];//皮重
		$data4['eweight']=$_REQUEST['eweight'];//毛重
		$data4['Factorynetweight']=$sweight;//出厂净重
		$data4['carstat']=$_REQUEST['carstat'];
		$result4=$model4->save ($data4);
		//更新拟定调度表信息
		$result3 = $model2->where('id='.$ControlTable['contractlogid'])->save($datactlog);
		//写入调度信息
		$n=$_SESSION['loginUserName'] ;//当前操作人	
		$data['control']=$_REQUEST['id'];//对应的调度信息ID
		$data['logtime']=date('YmdHis');//用于调度进度显示的时间
		$data['log']='订单号为：'.$orders.'被'.$n.'录入吨数，毛重：'.$_REQUEST['eweight'].'皮重：'.$_REQUEST['sweight'];//用于调度进度显示的记录
		$result5=$model5->add($data);
		if (($result!==false) && ($result1!==false)&&($result4!==false) && ($result5!==false)&&($result3!==false)&&($RSMDM!==false)&&($RSMJH!==false)&&($RSMNC!==false)) {
			$model2->commit (); // 提交事务
			$this->error ( '信息添加成功！','__URL__/index' );
		} else {
			$model2->rollback ();
			$this->error ( '数据库操作出错请联系管理员!' );
		}
}
//26日更新前 吨数录入 之后需要删除
public function oldupdateton() {
	$id=$_REQUEST['id'];
	$carstat=$_REQUEST['carstat'];
	$sweight=bcsub($_REQUEST['eweight'],$_REQUEST['sweight'],4);// 出厂净重=毛重-皮重
	$model = M ( 'Provider' );
	$model->startTrans();
	$result=true;
	$result1 = true;
	$RSMDM = true;
	$RSMNC = true;
	$RSMJH = true;
	$model3 = M ( "StoreManage" );
	$model4 = M('ControlTable');
	$ControlTable=$model4->where('id='.$id)->find();
	$providername = $ControlTable['provider'];//供应商
	$shipper = $ControlTable['shipper']; // 发货方
	$customer = $ControlTable['customer']; // 客户
	$product = $ControlTable['product']; // 产品名称
	$start = $ControlTable['start']; // 起始地
	$destination = $ControlTable['destination']; // 目的地
	$carrier = $ControlTable['carrier']; // 承运方
	$carno = $ControlTable['carno']; // 车牌号
	$orders = $ControlTable['orders']; // 订单号
	// 修改供应商供应表信息
	$Provider = $model->where ( 'id=\'' . $providername . '\'' )->find ();
	if (""==$providername||($Provider['providername']=="南曹库")||($Provider['providername']=="东明库")||($Provider['providername']=="金海库")) {
		$storenameA='storeA';
		$storenameB='storeB';
		$storenameC='storeC';
		// 当起始地或供应商选择为仓库时
		if ($start == "东明库") {
			if($destination=="东明库"){
				$model->rollback();
				$this->error ("起始地目的地不能同时为东明库！");
			}else{
				$Astoremanage = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameA.'\'' )->select ();
				if ($Astoremanage) {
					$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
					if ($datage ['stock'] < 0) {
						$model->rollback();
						$this->error ("东明库存不足！");
					}else{
						$RSMDM = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameA.'\'' )->save($datage);
					}
				} else {
					$model->rollback();
					$this->error ('东明库列表不存在' . $product . '相关物品!');
				}
			}
		}
		if ($start == "南曹库") {
			if($destination == "南曹库"){
				$model->rollback();
				$this->error ("起始地目的地不能同时为南曹库！");
			}else{
				$Astoremanage = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameB.'\'' )->select ();
				if ($Astoremanage) {
					$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
					if ($datage ['stock'] < 0) {
						$model->rollback();
						$this->error ('南曹库库存不足！');
					}else{
						$RSMNC = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameB.'\'' )->save($datage);
					}
				} else {
					$model->rollback();
					$this->error ('南曹库列表不存在' . $product . '相关物品!');
				}
			}
		}
		if ($start == "金海库") {
			if($destination == "金海库"){
				$model->rollback();
				$this->error ("起始地目的地不能同时为金海库！");
			}else{
				$Astoremanage = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameC.'\'' )->select ();
				if ($Astoremanage) {
					$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
					if ($datage ['stock'] < 0) {
						$model->rollback();
						$this->error ('金海库库存不足！');
					}else{
						$RSMJH = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameC.'\'' )->save($datage);
					}
				} else {
					$model->rollback();
					$this->error ('金海库列表不存在' . $product . '相关物品!');
				}
			}
		}
	}else{
		if ($shipper == "普天") {
			$data ['wshipment1'] = bcsub($Provider ['wshipment1'],$sweight,4);
			$i = 1;
		} else {
			if ($shipper == "兰亭") {
				$data ['wshipment2'] = bcsub($Provider ['wshipment2'],$sweight,4);
				$i = 2;
			} else {
				if ($shipper == "天地") {
					$data ['wshipment3'] = bcsub($Provider ['wshipment3'],$sweight,4);
					$i = 3;
				}
			}
		}
		if ($data ['wshipment' . $i] < 0) {
			$model->rollback();
			$this->error ($shipper."对应的供应商无足够货物可用");
		} else {
			$result = $model->where ( 'id=\'' . $providername . '\'' )->save ( $data );
		}
	}
	// 增加租车信息
	if (""!==$ControlTable['carrier']) {
		$model1 = M ( 'CarrierDispatch' );

		$map ['carrierid'] = $carrier;
		$map ['sendername'] = $shipper;
		$map ['customer'] = $customer;
		$map ['providername'] = $providername;
		$map ['carno'] = $carno;
		$map ['beginning'] = $start;
		$map ['destination'] = $destination;
		$map ['cweight'] = $sweight;
		$map ['status'] = 0;
		$map ['orders'] = $orders;

		$result1 = $model1->add ( $map );
	}
	//当客户选项或目的地选择为:仓库 时
	if ($customer == "东明库" || $destination == "东明库") {
		$storemanagedata = $model3->where('storename=\''.$storenameA.'\'')->getByProduct ( $product );
		if (! $storemanagedata) {
			$model->rollback();
			$this->error ('东明库列表不存在' . $product . '相关物品!');
		}
	}
	//南曹库判断
	if ($customer == "南曹库" || $destination == "南曹库") {
		$storemanagedata = $model3->where('storename=\''.$storenameB.'\'')->getByProduct ( $product );
		if (! $storemanagedata) {
			$model->rollback();
			$this->error ('南曹库列表不存在' . $product . '相关物品!');
		}
	}

	//金海库判断
	if ($customer == "金海库" || $destination == "金海库") {
		$storemanagedata = $model3->where('storename=\''.$storenameC.'\'')->getByProduct ( $product );
		if (! $storemanagedata) {
			$model->rollback();
			$this->error ('金海库列表不存在' . $product . '相关物品!');
		}
	}
	$data4['id']=$_REQUEST['id'];
	$data4['sweight']=$_REQUEST['sweight'];//皮重
	$data4['eweight']=$_REQUEST['eweight'];//毛重
	$data4['Factorynetweight']=$sweight;//出厂净重
	$data4['carstat']=$_REQUEST['carstat'];
	$result4=$model4->save ($data4);

	//写入调度信息
	$model5=M('ControlLog');
	$n=$_SESSION['loginUserName'] ;//当前操作人
	$data['control']=$_REQUEST['id'];//对应的调度信息ID
	$data['logtime']=date('YmdHis');//用于调度进度显示的时间
	$data['log']='订单号为：'.$orders.'被'.$n.'录入吨数，毛重：'.$_REQUEST['eweight'].'皮重：'.$_REQUEST['sweight'];//用于调度进度显示的记录
	$result5=$model5->add($data);
	if (($result!==false) && ($result1!==false)&&($result4!==false) && ($result5!==false)&&($RSMDM!==false)&&($RSMJH!==false)&&($RSMNC!==false)) {
		$model->commit (); // 提交事务
		$this->error ('信息添加成功！');
	} else {
		$model->rollback ();
		$this->error ('数据库操作出错请联系管理员!');
	}
}

	public function _before_update() {
		$ctlog = M('ContractLog');
		$type = $_REQUEST ['type'];
		$id = $_REQUEST ['id'];
		$model = M ( 'Provider' );
		$model1 = M ( 'ControlTable' );
		$model1->startTrans();//开启事务
		$model2 = M ( 'Freight' );
		$model3 = M ( 'CarrierDispatch' );
		$model4 = M ( 'Unload' );
		$model5 = M ( "StoreManage" );
		$result3 = true;
		$RCD = true;
		$RDM = true;
		$RNC = true;
		$RJH = true;
		$RP = true;
		$sweight = bcsub($_REQUEST ['eweight'],$_REQUEST ['sweight'],4); // 出厂净重=毛重-皮重
		$Con = $model1->where ( 'id=' . $id )->find ();
		//判断输入的吨数是否大于拟定调度要求的可调度吨数
		$ContractLog = $ctlog->find($Con['contractlogid']);
		if(empty($Con['contractlogid'])){
			$this->oldupdateton();
		}else{
			//拟定调度表可调度吨数
			$capacity = $ContractLog['capacity'];
			//拟定调度表已调度吨数
			$alshipment = $ContractLog['alshipment'];
			//获得修改前出厂净重
			$pre=$Con['Factorynetweight'];
			$subs=bcsub($sweight,$pre,4);
			//本次调度后已调度吨数
			$afteralshipment=bcadd($alshipment,$subs,4);
			$datactlog['alshipment']=$afteralshipment;
			$datactlog['status'] = ($datactlog['alshipment']/$capacity)*100;
			//更新拟定调度表信息
			$result3 = $ctlog->where('id='.$Con['contractlogid'])->save($datactlog);
		}
		$orders=$Con['orders'];
		//起始地
		$start=$_REQUEST['start'];
		//目的地
		$destination = $_REQUEST['destination'];
		//供应商
		$providerid = $Con['provider'];
		//按照修改的毛重与皮重，计算修改后的出厂净重
		$_POST['Factorynetweight']=$sweight;
		// 修改后出厂净重差值
		$Difference = bcsub($Con['Factorynetweight'],$sweight,4);
		
		//租车信息修改存入map中
		$map ['cweight'] = $sweight;//出厂净重
		$map ['status'] = 0;
		$map ['beginning'] = $start;
		$map ['destination'] = $destination;
		//查看是否已经有订单号的卸车和承运商结算记录
		$status = $model3->where ( 'orders=' . $orders )->getField ( 'status' );
		$Unloaddata = $model4->getByOrders ( $orders);
		if((0==$Con['sweight']&&null==$Con['sweight'])&&(0==$Con['eweight']&&null==$Con['eweight'])&&(0==$Con['Factorynetweight']&&null==$Con['Factorynetweight'])){
			$model1->rollback();
			$this->error('该调度还没有输入吨数信息不能修改！');
		}else
		{
			$provider = $model->where('id='.$providerid)->find();
			//客户
			$customer = $Con['customer'];
			if($provider['providername']=='东明库'){
				if($start!=='东明库'){
					$model1->rollback();
					$this->error('供应商为东明库时起始地只能为东明库！');
				}
			}
			if($provider['providername']=='南曹库'){
				if($start!=='南曹库'){
					$model1->rollback();
					$this->error('供应商为南曹库时起始地只能为南曹库！');
				}
			}
			if($provider['providername']=='金海库'){
				if($start!=='金海库'){
					$model1->rollback();
					$this->error('供应商为金海库时起始地只能为金海库！');
				}
			}
			if($customer=='东明库'){
				if($destination!=='东明库'){
					$model1->rollback();
					$this->error('供应商为东明库时起始地只能为东明库！');
				}
			}
			if($customer=='南曹库'){
				if($destination!=='南曹库'){
					$model1->rollback();
					$this->error('供应商为南曹库时起始地只能为南曹库！');
				}
			}
			if($customer=='金海库'){
				if($destination!=='金海库'){
					$model1->rollback();
					$this->error('供应商为金海库时起始地只能为金海库！');
				}
			}
		if (! $Unloaddata && ('0' == $status)) {
			$storenameA='storeA';
			$storenameB='storeB';
			$storenameC='storeC';
			$product=$Con['product'];
			//更新租车信息
			$RCD = $model3->where ( 'orders=' . $orders )->save ( $map );
			$Provider = $model->where ( 'id=\'' . $Con ['provider'] . '\'' )->find ();
			if ($Provider['providername']=="东明库"){
				$Astoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\''.$storenameA.'\'' )->select ();
				if ($Astoremanage) {
					$datage ['stock'] = $Astoremanage [0]['stock']+$Difference;
					if ($datage ['stock'] < 0) {
						$model1->rollback();
						$this->error ('东明库存不足！');
					}else{
						$RDM = $model5->where ( 'product=\'' . $product . '\' and storename=\''.$storenameA.'\'' )->save($datage);
					}
				} else {
					$model1->rollback();
					$this->error ('东明库列表不存在' . $product . '相关物品!');
				}
			}
			else{
				if($Provider['providername']=="南曹库"){
					$Astoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\''.$storenameB.'\'' )->select ();
					if ($Astoremanage) {
						$datage ['stock'] = $Astoremanage [0]['stock']+$Difference;
						if ($datage ['stock'] < 0) {
							$model1->rollback();
							$this->error ('南曹库存不足！');
						}else{
							$RNC = $model5->where ( 'product=\'' . $product . '\' and storename=\''.$storenameB.'\'' )->save($datage);
						}
					} else {
						$model1->rollback();
						$this->error ( '南曹库列表不存在' . $product . '相关物品!' );
					}
				}else{
					if($Provider['providername']=="金海库"){
						$Astoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\''.$storenameC.'\'' )->select ();
						if ($Astoremanage) {
							$datage ['stock'] = $Astoremanage [0]['stock']+$Difference;
							if ($datage ['stock'] < 0) {
								$model1->rollback();
								$this->error ('金海库存不足！');
							}else{
								$RJH = $model5->where ( 'product=\'' . $product . '\' and storename=\''.$storenameC.'\'' )->save($datage);
							}
						} else {
							$model1->rollback();
							$this->error ('金海库列表不存在' . $product . '相关物品!');
						}
					}else{
						if ($Con['shipper'] == "普天") {
							$data ['wshipment1'] = $Provider ['wshipment1'] + $Difference;
							$i = 1;
						} else {
							if ($Con['shipper'] == "兰亭") {
								$data ['wshipment2'] = $Provider ['wshipment2'] + $Difference;
								$i = 2;
							} else {
								if ($Con['shipper'] == "天地") {
									$data ['wshipment3'] = $Provider ['wshipment3'] + $Difference;
									$i = 3;
								}
							}
						}
						if ($data ['wshipment' . $i] < 0) {
							$model1->rollback();
							$this->error ( "供应商无足够货物可用");
						} else {
							//更新供应商吨数信息
							$RP = $model->where ( 'id=\'' . $Con['provider'] . '\'' )->save ( $data );
						}
					}
				}
			}
		}else {
			if ('1' == $status) {
			$model1->rollback();
			$this->error ("相关租车信息已经付过款，不能修改调度信息！");
			} else {
			if ($Unloaddata){
			$model1->rollback();
		    $this->error ("相关调度信息已经卸过车，不能修改调度信息！");
			}
			}
		}
		}
		//写入调度信息
		$model6=M('ControlLog');
		$n=$_SESSION['loginUserName'] ;//当前操作人
		$data['control']=$_REQUEST['id'];//对应的调度信息ID
		$data['logtime']=date('YmdHis');//用于调度进度显示的时间
		$data['log']='修改调度，订单号为：'.$orders.'被'.$n.'录入吨数，毛重：'.$_REQUEST['eweight'].'皮重：'.$_REQUEST['sweight'];//用于调度进度显示的记录
		$result5=$model5->add($data);
		if(($result5!==false)&&($RCD!==false)&&($RDM!==false)&&($result3!==false)&&($RJH!==false)&&($RNC!==false)&&($RP!==false)){
			$model1->commit();
		}else{
			$model1->rollback();
			$this->error("修改失败，请联系管理员");
		}
	}
	
	/**
	 * 接受页面传来的参数调用删除功能
	 */
	public function _before_foreverdelete() {
		$id = $_REQUEST ['ids'];
		$CT = M ( 'ControlTable' );
	    $CT->startTrans();
		$RCL = $this->UpwardReductionContractLog($id);
		$Rcondelete =  $this->controdelete($id);
		if(($RCL!==false)&&($Rcondelete!==false)){
			$CT->commit();
		}else{
			$CT->rollback();
			$this->error("删除失败,请联系管理员");
		}
	}
	/**
	 * 如果已经装车（录入吨数）删除调度操作之后向上还原拟定调度的已调度数
	 * 需要传递上级的ID[]
	 * @param $id 调度表的ID
	 */
	public function UpwardReductionContractLog($id){
		$model1 = M('ContractLog');
		$model2 = M ( 'ControlTable' );
		$ControlTableid = explode ( ',', $id );
		$k = count ( $ControlTableid );
		$RCL = true;
		for($j = 0; $j < $k; $j ++) {
			$ControlTable = $model2->where ( 'id=' . $ControlTableid [$j] )->find ();
			//需要还原的吨数
			$tunnage = $ControlTable['Factorynetweight'];
			//上级拟定调度表的ID
			$contractlogid = $ControlTable['contractlogid'];
			if($contractlogid){
				$ContractLog = $model1->find($contractlogid);
				//拟定调度表可调度吨数
				$capacity = $ContractLog['capacity'];
				//拟定调度表已调度吨数
				$alshipment = $ContractLog['alshipment'];
				//收集信息
				$datactlog['alshipment']=bcsub($alshipment, $tunnage,4);//删除后调度的表已调度数增加
				$datactlog['status'] = ($datactlog['alshipment']/$capacity)*100;
				$RCL = $model1->where('id='.$contractlogid)->save($datactlog);
				if($RCL == false){
					return $RCL;
				}
			}
		}
		return $RCL;
	}
		/**
	 * 调度的删除功能
	 * @param $id
	 */
	public function controdelete($id){
		$model1 = M ( 'ControlTable' );
		$model2 = M ( 'CarrierDispatch' );
		//事务交上级处理
		//$model2->startTrans (); // 开启事务
		$model3 = M ( 'Unload' );
		$model4 = M ( "StoreManage" );
		$result=true;
		$result1 = true;
		$result2 = true;
		$result3 = true;
		if(is_array($id)){
			$condition = $id;
				
		}else{
			$condition = explode ( ',', $id );
		}
		$k = count ( $condition );
		for($j = 0; $j < $k; $j ++) {
			$ControlTable = $model1->where ( 'id=' . $condition [$j] )->find ();
			$shipper = $ControlTable ['shipper'];
			$start = $ControlTable['start'];//起运地
			$product = $ControlTable['product']; // 产品名称
			$sweight = $ControlTable['Factorynetweight'];//出厂净重
				
			// 还原供货商的剩余量
			$model = M ( 'Provider' );
			$Provider = $model->field ( 'id,providername,wshipment1,wshipment2,wshipment3' )->where ( 'id=\'' . $ControlTable ['provider'] . '\'' )->find ();
			//当供应商为仓库时
			//当供应商或者起运地为仓库时还原仓库吨数
			$result=true;
			if(($Provider['providername']=="东明库")||($start=='东明库')){
				$smdata = $model4->getByProduct ( $product );
				$storename='storeA';
				if ($smdata) {
					$Astoremanage = $model4->where ( 'product=\'' . $product . '\' and storename=\''.$storename.'\'' )->select ();
					$datage ['stock'] = bcadd($Astoremanage [0] ['stock'],$sweight,4);
				} else {
					$this->error ('东明库列表不存在' . $product . '相关物品!');
				}
			}else{
				if(($Provider['providername']=="南曹库")||($start=='南曹库')){
					$smdata = $model4->getByProduct ( $product );
					$storename='storeB';
					if ($smdata) {
						$Astoremanage = $model4->where ( 'product=\'' . $product . '\' and storename=\''.$storename.'\'' )->select ();
						$datage ['stock'] = bcadd($Astoremanage [0] ['stock'],$sweight,4);
					} else {
						$this->error ('南曹库列表不存在' . $product . '相关物品!');
					}
				}else{
					if(($Provider['providername']=="金海库")||($start=='金海库')){
						$smdata = $model4->getByProduct ( $product );
						$storename='storeC';
						if ($smdata) {
							$Astoremanage = $model4->where ( 'product=\'' . $product . '\' and storename=\''.$storename.'\'' )->select ();
							$datage ['stock'] = bcadd($Astoremanage [0] ['stock'],$sweight,4);
						} else {
							$this->error ('南曹库列表不存在' . $product . '相关物品!' );
						}
					}else{
						if ($shipper == "普天") {
							$data ['wshipment1'] = $Provider ['wshipment1'] + bcsub($ControlTable ['eweight'],$ControlTable ['sweight'],4);
							$i = 1;
						} else {
							if ($shipper == "兰亭") {
								$data ['wshipment2'] = $Provider ['wshipment2'] + bcsub($ControlTable ['eweight'],$ControlTable ['sweight'],4);
								$i = 2;
							} else {
								if ($shipper == "天地") {
									$data ['wshipment3'] = $Provider ['wshipment3'] + bcsub($ControlTable ['eweight'],$ControlTable ['sweight'],4);
									$i = 3;
								}
							}
						}
					}
				}
			}
			$status = $model2->where ( 'orders=' . $ControlTable ['orders'] )->getField ( 'status' );
			$Unloaddata = $model3->getByOrders ( $ControlTable ['orders'] );
			// 删除对应的租车信息，当租车信息付过款式不能删除,除非用户为admin
			if ((! $Unloaddata && ('0' == $status))||('1'==$_SESSION [C ( 'USER_AUTH_KEY' )])) {
				if($data){
					$result1 = $model->where ( 'id=\'' . $ControlTable ['provider'] . '\'' )->save ( $data );
				}
				if($datage){
					$result2 = $model4->where ( 'product=\'' . $product . '\' and storename=\''.$storename.'\'' )->save($datage);
				}
				//删除卸车记录
				$result3 = $model3->where ( 'orders=' . $ControlTable ['orders'] )->delete ();
				$result = $model2->where ( 'orders=' . $ControlTable ['orders'] )->delete ();
				//$model->commit (); // 提交事务
			} else {
				if ('1' == $status) {
					$this->error ("相关租车信息已经付过款，不能删除调度信息！");
				} else {
					if ($Unloaddata){
						$this->error ("相关调度信息已经卸过车，不能删除调度信息！" );
					}
				}
			}
		}
		if(($result!==false)&&($result1!==false)&&($result2!==false)){
			return true;
		}else{
			return false;
		}
	}
	//允许卸货
	public function unload(){
		$id = $_REQUEST ['id'];
		$model=M('ControlTable');
		$data['payondelivery']='0';
			if($model->where('id='.$id)->getField('payondelivery')=='0'){
				$this->error( '已允许过!');
			}else{
				if ($model->where ('id='.$id)->save($data)) {
					$this->error ('允许成功!');
				} else {
					$this->error ('允许失败!');
				}
			}
		
	}
	
	function add(){
		$ajax = $_REQUEST['ajax'];
		if($ajax=='a'){
			$this->customerajax();
		}else{
			$this->display("add");
		}
		
	}
	
	//判断是否为款到卸车
	public function customerajax(){
		$arr = $_REQUEST;
		$model = M('Customer');
		$customer = $model->where('id='.$arr['customer'])->find();
		$payondelivery = $customer['payondelivery'];
		$map['status']='';
		if($payondelivery){
			$map['status']="<spen style='color:red'>注意：本客户为款到卸车!</spen>";
		}
		if(function_exists("json_encode")){
			echo json_encode($map);
		}
	}	
	/**
	 * 拟定调度
	 */
	public function BlockOutcontrol() {
		if("true"==$_REQUEST['add']){
			$this->_before_add();
			$this->add();
		}else{
			if("true"==$_REQUEST['insert']){
				$this->_before_insert();
				$this->insert();
			}else{
				$model=M('ContractLog');
				$userid=$_SESSION [C ( 'USER_AUTH_KEY' )];
				//$sql = "select * from mlt_contract_log conlog where status!=100 and conlog.id in(select controllogid from mlt_controllog_user conuser where userid=".$userid.") order by capatime desc";
				$sql = "select * from mlt_contract_log conlog  where status!=100   and capacity!=0 order by capatime desc";
				$result = $model->query($sql);
				$this->assign('list',$result);
				$this->display();
			}
		}
	}
}
